<!--
/**
* @description 登录页面
* @author wind-lc
* @date 2020-05-29
*/
-->
<template>
  <a-spin wrapperClassName="login-spin"
          tip="正在登录..."
          :spinning="ddLoading">
    <div class="sign-in-container">
      <div class="sign-in-title">
        <img src="@/assets/img/logo.png"
             alt="数智环境+电力大数据监管平台">
        <h1>
          <span>数智环境</span>
          <span class="sign-in-title-line"></span>
          <span>电力大数据监管平台</span>
        </h1>
      </div>
      <div class="sign-in-form-wrapper">
        <div :class="isDD? 'sign-in-form dd-sign-in-form': 'sign-in-form'">
          <h3 class="sign-in-form-welcome">欢迎登录</h3>
          <a-form-model :model="form"
                        ref="form"
                        :rules="rules"
                        @submit.native.prevent>
            <a-form-model-item prop="username">
              <a-input v-model.trim="form.username"
                       autocomplete="off"
                       placeholder="请输入用户名"
                       :maxLength="20">
                <icon-svg slot="prefix"
                          type="icon-icon-"></icon-svg>
              </a-input>
            </a-form-model-item>
            <a-form-model-item prop="password">
              <a-input v-model="form.password"
                       type="text"
                       placeholder="请输入密码"
                       autoComplete="new-password"
                       @compositionend="handlePassword"
                       :maxLength="20"
                       class="sign-in-password"
                       oncut="return false"
                       onpaste="return false"
                       oncontextmenu="return false">
                <icon-svg slot="prefix"
                          type="icon-xiugaimima"></icon-svg>
              </a-input>
            </a-form-model-item>
            <a-checkbox class="sign-in-form-rememb"
                        :checked="remember"
                        @change="changeRemember">记住密码</a-checkbox>
            <a-form-model-item>
              <a-button block
                        type="primary"
                        @click="handleSubmit"
                        :loading="loading">登录</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </div>
  </a-spin>
</template>
<script>
import { FormModel, Input, Checkbox, Button, Spin } from 'ant-design-vue'
import IconSvg from '@/components/IconSvg'
import { setLocalStorage, getLocalStorage } from '@/utils'
import { doSm3AndSm2Encrypt } from '@/utils/sm'
import { grantType, clientId, clientSecre, appKey, appSecret, corpId } from '@/config/index'
import { getUserBaseInfoJson, getAccessToken, getLoginUser } from '@/request/api/permissionManagement/user/user'
import * as dd from 'dingtalk-jsapi'
export default {
  name: 'signIn',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ACheckbox: Checkbox,
    AButton: Button,
    IconSvg,
    ASpin: Spin
  },
  data () {
    return {
      // 登录表单
      form: {
        password: ''
      },
      pwd: '',
      // 校验
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'change'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'change'
          }
        ]
      },
      // 是否记密码
      remember: false,
      // 按钮loading
      loading: false,
      // dd免登录loading
      ddLoading: false,
      // 是否dd环境
      isDD: false
    }
  },
  mounted () {
    this.getLocalInfo()
    this.ddLogin()
  },
  methods: {
    // 钉钉获取免登授权码
    ddLogin () {
      // 判断环境是否钉钉环境下
      if (dd.env.platform !== 'notInDingTalk') {
        this.ddLoading = true
        this.isDD = true
        dd.ready(() => {
          dd.runtime.permission.requestAuthCode({
            corpId, // 企业id
            onSuccess: (info) => {
              // 通过该免登授权码可以获取用户身份
              this.getUserBaseInfoJson(info.code)
            },
            onFail: () => {
              this.ddLoading = false
              this.$message.error('获取免登授权码失败')
            }
          })
        })
      } else {
        console.log(dd, 'dd')
      }
    },
    // 使用code到统一授权中心注册用户信息
    getUserBaseInfoJson (code) {
      getUserBaseInfoJson({
        code,
        appKey
      }).then((res) => {
        if (res.success) {
          this.getAccessToken(code)
        } else {
          this.ddLoading = false
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.ddLoading = false
        this.$message.error('登录用户注册失败')
      })
    },
    // 子系统AccessToken获取
    getAccessToken (code) {
      getAccessToken({
        appSecret,
        appKey
      }).then((res) => {
        if (res.success) {
          this.getLoginUser(res.result.accessToken, code)
        } else {
          this.ddLoading = false
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.ddLoading = false
        this.$message.error('AccessToken获取失败')
      })
    },
    // 使用AccessToken和code进行登录
    getLoginUser (accessToken, code) {
      getLoginUser({ accessToken, code }).then((res) => {
        // this.$message.info(JSON.stringify(res))
        if (res.success) {
          this.asyncLogin({
            username: res.result.mobile,
            password: '123456'
          })
        } else {
          this.ddLoading = false
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.ddLoading = false
        this.$message.error('使用AccessToken和code进行登录失败')
      })
    },
    // 获取账号密码
    getLocalInfo () {
      const info = getLocalStorage('kjfduwedszhmm')
      // 有无信息
      if (info) {
        this.remember = true
        // 写入文本域
        this.form = {
          username: atob(atob(info.jdi287dsn)),
          password: atob(atob(info.poodm23sp))
        }
      } else {
        this.remember = false
      }
    },
    asyncLogin ({ username, password }) {
      const params = {
        grant_type: grantType,
        client_id: clientId,
        client_secret: clientSecre,
        username,
        password: doSm3AndSm2Encrypt(password)
      }
      this.$store
        .dispatch('login', Object.assign({}, params))
        .then(res => {
          if (res.code) {
            const query = Object.assign({}, params, {
              code: res.code
            })
            this.$store
              .dispatch('loginSys', query)
              .then(res => {
                // 用户信息
                this.$store.dispatch('generateRoutes').then(res => {
                  // 跳转主页
                  this.$router.push('/')
                  // 记住密码
                  if (this.remember) {
                    setLocalStorage('kjfduwedszhmm', {
                      jdi287dsn: btoa(btoa(this.form.username)),
                      poodm23sp: btoa(btoa(this.form.password))
                    })
                  }
                }).catch(error => {
                  this.loading = false
                  this.ddLoading = false
                  console.log(error)
                })
              })
              .catch(error => {
                this.loading = false
                this.ddLoading = false
                this.$message.error(error.error_description)
                // 修改默认密码
                if (
                  error.response.data.code === '4004' &&
                  error.response.data.error_description ===
                  '不能使用默认密码登录，请修改密码后再登录'
                ) {
                  this.$router.push('/editOriginalPwa')
                }
              })
          }
        })
        .catch(error => {
          this.loading = false
          this.ddLoading = false
          console.log(error)
          // this.$message.error(JSON.stringify(error))
        })
    },
    // 登录
    handleSubmit (e) {
      e.preventDefault()
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const params = {
            username: this.form.username,
            password: this.form.password
          }
          this.asyncLogin(params)
        }
      })
    },
    // 控制记住密码
    changeRemember (e) {
      this.remember = e.target.checked
      if (!this.remember) {
        localStorage.removeItem('kjfduwedszhmm')
      }
    },
    // 阻止输入法输入
    handlePassword () {
      event.target.value = event.target.value.replace(/[^A-Za-z0-9]/g, '')
    }

  }
}
</script>
<style lang="scss">
@font-face {
  font-family: 'password';
  src: url('~@/assets/font/passwordEntry.ttf');
}
.login-spin {
  height: 100%;
  .ant-spin-container {
    height: 100%;
  }
  div {
    .ant-spin {
      max-height: 100%;
    }
  }
}
.sign-in-container {
  background-color: rgba(0, 0, 0, 0.5);
  background-image: url('~@/assets/img/signInBg.jpg');
  background-repeat: no-repeat;
  height: 100%;
  background-size: cover;
  display: flex;
}
.sign-in-title {
  flex: 1;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: 3.54vw;
    height: 3.54vw;
  }
  h1 {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.66vw;
    color: #fff;
    span {
      margin-left: 18px;
    }
    .sign-in-title-line {
      display: block;
      width: 0.15vw;
      height: 1.56vw;
      background-color: #fff;
    }
  }
}
.sign-in-form-welcome {
  font-size: 1.66vw;
  text-align: center;
  width: 100%;
  margin-bottom: 70px;
}
.sign-in-form-wrapper {
  width: 31.25vw;
  height: 100%;
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;
}
.dd-sign-in-form {
  margin-top: 50%;
}
.sign-in-form {
  width: 17.1vw;

  .ant-input {
    height: 2.5vw;
    font-size: 0.93vw;
    &::placeholder {
      color: #d8d8d8;
    }
  }
  .ant-input-affix-wrapper .ant-input:not(:first-child) {
    padding-left: 54px;
  }
  .ant-input-affix-wrapper .ant-input-prefix {
    left: 22px;
  }
  .ant-form-item {
    margin-bottom: 30px;
  }
  .ant-form-item-with-help {
    margin-bottom: 4px;
  }
  .ant-form-explain {
    margin-top: 5px;
  }
  .ant-btn {
    height: 2.6vw;
    font-size: 1.04vw;
  }
  .ant-checkbox-wrapper span {
    color: #121d31;
  }
  input:-webkit-autofill {
    box-shadow: 0 0 0px 1000px #ffffff inset !important;
    -webkit-text-fill-color: #3e3e3e !important;
    font-size: 0.93vw;
  }
}
.ant-input-prefix .icon-svg {
  color: #1890ff;
  font-size: 1.04vw;
}
.sign-in-form-rememb {
  margin-bottom: 30px;
}
.sign-in-password {
  font-family: 'password';
}
</style>
